package com.example.demo2jsp;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.SimpleHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet(name = "helloServlet", value = "/hello-servlet")
public class Home extends HttpServlet {
    private String message;

    public void init() {
        System.out.println("生命周期函数init");
        message = "Hello World!";
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html");

        String SendUrl = "https://api.github.com/users";
        HttpClient httpclient = null;
        GetMethod post = null;
        try {
            httpclient = new HttpClient();
            post = new GetMethod(SendUrl);
            //设置编码方式
            post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
            //添加参数
            // post.addParameter("order", order);
            //执行
            httpclient.executeMethod(post);
            //接口返回信息
            String info = new String(post.getResponseBody(), "UTF-8");
            System.out.println("返回结果："+info);

            JSONObject obj = JSON.parseObject(info);

            HttpSession session = request.getSession();
            session.setAttribute("name", obj.get(""));
            session.setAttribute("age", 23);

            response.sendRedirect("login.jsp");
//            response.red
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭连接，释放资源
            post.releaseConnection();
            ((SimpleHttpConnectionManager) httpclient.getHttpConnectionManager()).shutdown();
        }

        // Hello
//        PrintWriter out = response.getWriter();
//        out.println("<html><body>");
//        out.println("<h1>" + message + "</h1>");
//        out.println("</body></html>");
    }

    public void destroy() {
    }
}